<template>
	<div>
		<el-form
			ref="ruleFormRef"
			:model="ruleForm"
			:rules="rules"
			label-width="120px"
			class="demo-ruleForm"
			status-icon
			scroll-to-error
			:validate-on-rule-change="false"
		>
			<el-card shadow="never">
				<div class="card-title">基本信息</div>
				<el-row :gutter="10">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="请选择路线" prop="line_id">
							<el-select @change="changeLine()" style="width: 100%" v-model="ruleForm.line_id" placeholder="请选择路线">
								<el-option
									v-for="(item, index) in lineLists"
									:key="index"
									:label="item.start_country + item.start_country_code + ' ✈ ' + item.end_country + item.end_country_code"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="货物类型" prop="goods_type_id">
							<el-select style="width: 100%" v-model="ruleForm.goods_type_id" placeholder="选择路线后选择">
								<el-option v-for="(item, index) in goodsTypeList" :key="index" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col> -->
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="渠道:" prop="channel_id">
							<el-select style="width: 100%" v-model="ruleForm.channel_id" placeholder="选择路线后选择">
								<el-option
									style="margin-bottom: 15px; border-top: 1px solid #d6d6d6; border-bottom: 1px solid #d6d6d6"
									v-for="(item, index) in channelList"
									:key="index"
									:label="item.name"
									:value="item.id"
								/>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="请选择客户" prop="client_id">
							<div style="display: flex; justify-content: space-between; width: 100%">
								<el-select
									:disabled="is_san"
									style="width: 100%; margin-right: 10px"
									v-model="ruleForm.client_id"
									placeholder="请选择客户"
									@change="changeUser"
								>
									<el-option v-for="(item, index) in userLists" :key="index" :label="item.username" :value="item.id" />
								</el-select>
								<el-checkbox v-model="is_san" label="散客" />
							</div>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="唛头" prop="user_mark">
							<el-input v-model="ruleForm.user_mark" placeholder="请填写唛头" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="产品类型" prop="express_type">
							<div style="display: flex; align-items: center; justify-content: space-between; width: 100%">
								<el-select style="width: 100%" v-model="ruleForm.express_type" placeholder="选择路产品类型">
									<el-option label="标快" :value="1" />
									<el-option label="特快" :value="2" />
								</el-select>
								<el-tooltip
									class="box-item"
									effect="dark"
									content="快递产品类型提示：目前对走顺丰的订单产生影响"
									placement="top-start"
								>
									<el-icon :size="18" style="margin-left: 10px; cursor: pointer">
										<QuestionFilled />
									</el-icon>
								</el-tooltip>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>
			<el-card shadow="never" style="margin-top: 10px">
				<div style="display: flex">
					<div style="width: 50%">
						<div class="card-title">寄件人</div>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="智能识别:" prop="aiAddressSender">
									<div style="display: flex; width: 100%">
										<el-input style="width: 80%" placeholder="请填写要识别的信息" v-model="aiAddressSender" />
										<el-button style="flex: 1; margin-left: 10px" @click="searchAiMessage('aiAddressSender')" type="primary"
											>查 询</el-button
										>
									</div>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="姓名:" prop="sender.name">
									<el-input placeholder="请填写寄件人姓名" v-model="ruleForm.sender.name" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="区号:" prop="sender.area_code">
									<el-select style="width: 100%" v-model="ruleForm.sender.area_code" class="m-2" placeholder="请选择区号">
										<el-option
											v-for="item in codeList"
											:key="item.area_code"
											:label="'+' + item.area_code + ' ' + item.area_name"
											:value="item.area_code"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="手机:" prop="sender.mobile">
									<el-input placeholder="请填写手机" v-model="ruleForm.sender.mobile" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="邮编:" prop="sender.postcode">
									<el-input placeholder="请填写邮编" v-model="ruleForm.sender.postcode" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="填写区域:" prop="sender.nation">
									<div style="display: flex">
										<el-input style="margin-right: 10px" placeholder="请填写国家" v-model="ruleForm.sender.nation" />
										<el-input style="margin-right: 10px" placeholder="请填写省" v-model="ruleForm.sender.province" />
										<el-input style="margin-right: 10px" placeholder="请填写市" v-model="ruleForm.sender.city" />
										<el-input placeholder="请填写区" v-model="ruleForm.sender.district" />
									</div>

									<!-- <el-cascader
										filterable
										@change="changeAreaSender()"
										v-model="areaListSender"
										:props="codes"
										placeholder="请选择区域"
										:options="linkList"
										style="width: 100%"
									/> -->
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="地址:" prop="sender.detailed">
									<el-input
										placeholder="请填写地址"
										:autosize="{ minRows: 2, maxRows: 4 }"
										type="textarea"
										v-model="ruleForm.sender.detailed"
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</div>

					<div style="width: 50%">
						<div class="card-title">
							收件人
							<span
								@click="showAddress = true"
								v-if="ruleForm.client_id"
								style="margin-left: 52px; font-size: 14px; cursor: pointer"
								>选择地址</span
							>
						</div>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="智能识别:" prop="aiAddress">
									<div style="display: flex; width: 100%">
										<el-input style="width: 80%" placeholder="请填写要识别的信息" v-model="aiAddress" />
										<el-button style="flex: 1; margin-left: 10px" @click="searchAiMessage('client')" type="primary"
											>查 询</el-button
										>
									</div>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="姓名:" prop="client_address.name">
									<el-input placeholder="请填写收件人姓名" v-model="ruleForm.client_address.name" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="区号:" prop="client_address.area_code">
									<el-select style="width: 100%" v-model="ruleForm.client_address.area_code" class="m-2" placeholder="请选择区号">
										<el-option
											v-for="item in codeList"
											:key="item.area_code"
											:label="'+' + item.area_code + ' ' + item.area_name"
											:value="item.area_code"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
								<el-form-item label="手机:" prop="client_address.mobile">
									<el-input placeholder="请填写手机" v-model="ruleForm.client_address.mobile" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="邮编:" prop="client_address.postcode">
									<el-input placeholder="请填写邮编" v-model="ruleForm.client_address.postcode" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="选择区域:" prop="client_address.nation">
									<el-cascader
										filterable
										@change="changeArea()"
										v-model="areaList"
										:props="codes"
										placeholder="请选择区域"
										:options="linkList"
										style="width: 100%"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="地址:" prop="client_address.detailed">
									<el-input
										placeholder="请填写地址"
										:autosize="{ minRows: 2, maxRows: 4 }"
										type="textarea"
										v-model="ruleForm.client_address.detailed"
									/>
								</el-form-item>
							</el-col>
						</el-row>
					</div>
				</div>
			</el-card>
			<el-card shadow="never" style="margin-top: 10px">
				<div class="card-title">内物详情</div>
				<el-button style="margin-bottom: 10px" @click="addGoods()" type="primary">添加商品</el-button>
				<el-table :data="ruleForm.detail" style="width: 100%" border :header-cell-style="{ color: 'var(--el-color-primary)' }">
					<el-table-column prop="name" label="商品类目"> </el-table-column>
					<el-table-column prop="title" label="商品名称">
						<template #default="{ row }">
							<el-input placeholder="根据类目回显也可以自由编辑" v-model="row.title" />
						</template>
					</el-table-column>
					<el-table-column prop="amount" label="申报价值(KRW)">
						<template #default="{ row }">
							<el-input placeholder="申报价值(KRW)" v-model="row.amount" />
						</template>
					</el-table-column>
					<el-table-column prop="num" label="数量">
						<template #default="{ row }">
							<el-input placeholder="数量" v-model="row.num" />
						</template>
					</el-table-column>
					<el-table-column prop="address" label="小计(KRW)">
						<template #default="{ row }">
							{{ (row.num * row.amount).toFixed(2) }}
						</template>
					</el-table-column>
					<el-table-column label="操作" prop="addtime" width="100">
						<template #default="{ $index }">
							<el-button @click="delet($index)" type="primary">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="total">
					<div style="margin-right: 50px">
						商品数量: <span>{{ totalNum }}</span>
					</div>
					<div>
						商品金额合计: <span>{{ totalAmount }}</span>
					</div>
				</div>
			</el-card>
			<el-card shadow="never" style="margin-top: 10px">
				<div class="card-title">其 他</div>
				<el-row :gutter="10">
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="申报重量(kg):" prop="weight_report">
							<el-input placeholder="请填写包裹申报重量" v-model="ruleForm.weight_report" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
						<el-form-item label="来源单号:" prop="order_no">
							<el-input placeholder="请填来源单号" v-model="ruleForm.order_no" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="订单备注:" prop="remarks">
							<el-input
								placeholder="请填写订单备注"
								:autosize="{ minRows: 2, maxRows: 4 }"
								type="textarea"
								v-model="ruleForm.remarks"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-card>
			<div class="buttons">
				<el-button @click="resetForm(ruleFormRef)">清 空</el-button>
				<el-button style="margin-left: 50px" @click="submitOrder()" type="primary">完 成</el-button>
			</div>
		</el-form>
		<CateDialog @get-goods="getGoods" v-model:showDialog="show"></CateDialog>
		<AddressDialog @set-address="setDefaultAddress" v-model:showDialog="showAddress" :addressList="addressList"></AddressDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import CateDialog from "@/components/CateDialog/index.vue";
import { lineList, goodsListType, orderCreate, listChannel, AddressCorrect } from "@/api/modules/makeorder";
import { listClientNo, getClientAddress } from "@/api/modules/address";
import { countryAddressInfo, listMobileAreaCode, sender } from "@/api/base/index";
import AddressDialog from "./address.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { GlobalStore } from "@/stores";
const globalStore = GlobalStore();

const ruleFormRef = ref<FormInstance>();
const is_san = ref(false);
watch(is_san, () => {
	if (is_san.value) {
		(rules.client_id as any)[0].required = false;
		ruleForm.client_id = "";
		ruleForm.client_address_id = 0;
		// ruleForm.user_mark = "";
	} else {
		(rules.client_id as any)[0].required = true;
	}
});
const codes = {
	label: "name",
	value: "name",
	children: "_child"
};
const ruleForm = reactive({
	line_id: "",
	// goods_type_id: "", //货物类型
	channel_id: "",
	client_id: "",
	user_mark: "",
	client_address_id: 0,
	client_address: {
		name: "",
		area_code: "",
		mobile: "",
		postcode: "",
		nation: "",
		province: "",
		city: "",
		district: "",
		detailed: ""
	},
	sender: {
		name: "",
		area_code: "",
		mobile: "",
		postcode: "",
		nation: "",
		province: "",
		city: "",
		district: "",
		detailed: ""
	},
	detail: [],
	order_no: "",
	weight_report: "",
	remarks: "",
	express_type: 1
});
const totalNum = computed(() => {
	let num = 0;
	ruleForm.detail.forEach((row: any) => {
		num += Number(row.num);
	});
	return num;
});
const totalAmount = computed(() => {
	let num = 0;
	ruleForm.detail.forEach((row: any) => {
		num += row.num * row.amount;
	});
	return num.toFixed(2);
});

const addressList: any = ref([]);
const showAddress = ref(false);

//选中客户获取地址列表
const changeUser = () => {
	if (ruleForm.client_id) {
		//获取客户地址列表及默认地址
		getClientAddress({
			client_id: ruleForm.client_id
		}).then(res => {
			addressList.value = res.data;
			(res.data as any).forEach((item: any) => {
				if (item.is_default == 1) {
					ruleForm.client_address_id = item.id;
					areaList.value = [];
					if (item.nation) {
						areaList.value.push(item.nation, item.province, item.city, item.district);
					}
					Object.keys(ruleForm.client_address).forEach(i => {
						(ruleForm.client_address as any)[i] = item[i];
					});
					// changeArea();
				}
			});
		});

		userLists.value.forEach((element: any) => {
			if (element.id == ruleForm.client_id) {
				ruleForm.user_mark = element.user_mark;
			}
		});
	}
};
//获取商品
const getGoods = (item: any) => {
	(ruleForm.detail as any).push(item);
};

//选择地址
const setDefaultAddress = (item: any) => {
	ruleForm.client_address_id = item.id;
	areaList.value = [];
	if (item.nation) {
		areaList.value.push(item.nation, item.province, item.city, item.district);
	}
	Object.keys(ruleForm.client_address).forEach(i => {
		(ruleForm.client_address as any)[i] = item[i];
	});
	ruleForm.client_address.nation = areaList.value[0];
};

const rules = reactive<FormRules>({
	line_id: [{ required: true, message: "请选择路线" }],
	// goods_type_id: [{ required: true, message: "请选择货物类型" }],
	channel_id: [{ required: true, message: "请选择渠道" }],

	client_id: [{ required: true, message: "请选择客户" }],
	user_mark: [{ required: true, message: "请填写唛头" }],
	client_address_name: [{ required: true, message: "请填写收件人姓名" }],
	express_type: [{ required: true, message: "请选择路产品类型" }],

	// weight_report: [{ required: true, message: "请填写包裹申报重量" }],
	["client_address.name"]: [{ required: true, message: "请填写收件人姓名" }],
	["client_address.area_code"]: [{ required: true, message: "请选择区号" }],
	["client_address.mobile"]: [{ required: true, message: "请填写手机" }],
	["client_address.nation"]: [{ required: true, message: "请选择区域" }],
	// ["client_address.postcode"]: [{ required: true, message: "请填写邮编" }],
	["client_address.detailed"]: [{ required: true, message: "请填写地址" }],

	["sender.name"]: [{ required: true, message: "请填写寄件人姓名" }],
	["sender.area_code"]: [{ required: true, message: "请选择区号" }],
	["sender.mobile"]: [{ required: true, message: "请填写手机" }],
	["sender.nation"]: [{ required: true, message: "请选择区域" }],
	// ["sender.postcode"]: [{ required: true, message: "请填写邮编" }],
	["sender.detailed"]: [{ required: true, message: "请填写地址" }]
});
const aiAddress = ref("");
const aiAddressSender = ref("");

const searchAiMessage = (type: string) => {
	if (type == "aiAddressSender") {
		AddressCorrect({
			country: "CN",
			address: aiAddressSender.value
		}).then((res: any) => {
			areaList.value = [];
			areaList.value.push("中国", res.data.state, res.data.city, res.data.district);
			ruleForm.sender.nation = "中国";
			ruleForm.sender.province = res.data.state;
			ruleForm.sender.city = res.data.city;
			ruleForm.sender.district = res.data.district;
			ruleForm.sender.detailed = res.data.detail;
			ruleForm.sender.mobile = res.data.phone;
			ruleForm.sender.name = res.data.name;
		});
	} else {
		AddressCorrect({
			country: "CN",
			address: aiAddress.value
		}).then((res: any) => {
			areaList.value = [];
			areaList.value.push("中国", res.data.state, res.data.city, res.data.district);
			ruleForm.client_address.nation = "中国";
			ruleForm.client_address.province = res.data.state;
			ruleForm.client_address.city = res.data.city;
			ruleForm.client_address.district = res.data.district;
			ruleForm.client_address.detailed = res.data.detail;
			ruleForm.client_address.mobile = res.data.phone;
			ruleForm.client_address.name = res.data.name;
		});
	}
};
const goodsTypeList: any = ref([]);
const channelList: any = ref([]);

const changeLine = () => {
	// ruleForm.goods_type_id = "";
	ruleForm.channel_id = "";

	//获取货物类型
	// goodsListType({
	// 	line_id: ruleForm.line_id
	// }).then((res: any) => {
	// 	goodsTypeList.value = res.data.list;
	// });
	//获取渠道列表
	listChannel({
		line_id: ruleForm.line_id,
		limit: 1000
	}).then((res: any) => {
		channelList.value = res.data.list;
	});
};

const show = ref(false);
const addGoods = () => {
	show.value = true;
};
const delet = (index: any) => {
	ruleForm.detail.splice(index, 1);
};
const areaList = ref();
const areaListSender = ref();
const lineLists: any = ref([]);
const userLists: any = ref([]);
const linkList: any = ref([]);
//区号列表
const codeList: any = ref([]);
async function getcodeList() {
	let res: any = await listMobileAreaCode();
	return res.data.list;
}

onMounted(() => {
	getcodeList().then(res => {
		codeList.value = res;
	});
	sender({}).then((res: any) => {
		areaListSender.value = [];
		areaListSender.value.push(res.data.nation, res.data.province, res.data.city, res.data.district);
		ruleForm.sender.nation = res.data.nation;
		ruleForm.sender.province = res.data.province;
		ruleForm.sender.city = res.data.city;
		ruleForm.sender.postcode = res.data.postcode;
		ruleForm.sender.district = res.data.district;
		ruleForm.sender.detailed = res.data.detailed;
	});
	//获取线路列表
	lineList({}).then((res: any) => {
		lineLists.value = res.data.list;
		globalStore.setLineLists(lineLists.value);
	});
	//获取客户
	listClientNo({}).then((res: any) => {
		userLists.value = res.data;
	});
	if (globalStore.linkList.length) {
		linkList.value = globalStore.linkList;
	} else {
		countryAddressInfo({ id: 1 }).then(res => {
			linkList.value = res.data;
			globalStore.setLinkLists(linkList.value);
		});
	}
});
const changeArea = () => {
	areaList.value.push("");
	ruleForm.client_address.nation = areaList.value[0];
	ruleForm.client_address.province = areaList.value[1];
	ruleForm.client_address.city = areaList.value[2];
	ruleForm.client_address.district = areaList.value[3];
};
const changeAreaSender = () => {
	areaListSender.value.push("");
	ruleForm.sender.nation = areaList.value[0];
	ruleForm.sender.province = areaList.value[1];
	ruleForm.sender.city = areaList.value[2];
	ruleForm.sender.district = areaList.value[3];
};
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	areaList.value = [];
	areaListSender.value = [];
	channelList.value = [];
	goodsTypeList.value = [];
	ruleForm.detail = [];
	aiAddress.value = "";
	aiAddressSender.value = "";
	formEl.resetFields();
};
const submitOrder = () => {
	if (!ruleForm.detail.length) {
		ElMessage.error("请添加商品");
		return;
	}
	if (!ruleForm.client_address.nation) {
		ElMessage.error("请选择收件人区域");
		return;
	}
	ruleFormRef.value!.validate(async valid => {
		if (!valid) return;
		try {
			let param: any = { ...ruleForm };
			if (!param.client_id) {
				param.client_id = 0;
			}
			orderCreate(param).then(res => {
				ElMessageBox.alert("制单成功!", "提示", {
					// if you want to disable its autofocus
					// autofocus: false,
					confirmButtonText: "OK",
					callback: () => {
						// resetForm(ruleFormRef.value);
					}
				});
			});
		} catch (error) {
			console.log(error);
		}
	});
};
</script>

<style lang="scss" scoped>
.card-title {
	margin-bottom: 20px;
	color: var(--el-color-primary);
	&::before {
		position: relative;
		top: 2px;
		display: inline-block;
		width: 4px;
		height: 16px;
		margin-right: 6px;
		content: "";
		background-color: var(--el-color-primary);

		// color: ;
	}
}
.headers {
	background-color: var(--el-color-primary);
}
.total {
	display: flex;
	margin-top: 20px;
	font-size: 14px;
	span {
		margin-left: 5px;
		color: var(--el-color-primary);
	}
}
.buttons {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
</style>
